package com.xidian.zhiancloud.service.accidentManage;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.xidian.zhiancloud.constant.AccidentManagementConstant;
import com.xidian.zhiancloud.dao.AccidentHandleMapper;
import com.xidian.zhiancloud.dao.AccidentHandleSurveyTeamMapper;
import com.xidian.zhiancloud.dao.AccidentMessageMapper;
import com.xidian.zhiancloud.dao.SysOrganizationAbandonMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dto.accidentMessage.AccidentHandleDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.AccidentHandle;
import com.xidian.zhiancloud.model.AccidentHandleSurveyTeam;
import com.xidian.zhiancloud.model.AccidentMessage;
import com.xidian.zhiancloud.model.SysOrganizationAbandon;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.accidentmessage.AccidentHandleQO;
import com.xidian.zhiancloud.util.zyf.ExcelUtils;
import com.xidian.zhiancloud.vo.accidentmessage.AccidentHandleVO;
import com.xidian.zhiancloud.vo.accidentmessage.SurveyMemberVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
public class AccidentHandleService extends ServiceImpl<AccidentHandleMapper, AccidentHandle> implements IService<AccidentHandle> {

    @Autowired
    private AccidentHandleMapper accidentHandleMapper;

    @Autowired
    private AccidentMessageMapper accidentMessageMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private AccidentHandleSurveyTeamMapper accidentHandleSurveyTeamMapper;

    /**
     * 添加事故处理信息
     * @param accidentHandleDTO
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean addAccidentHandle(AccidentHandleDTO accidentHandleDTO){
        AccidentHandle accidentHandle = accidentHandleDTO.getAccidentHandle();

        LambdaQueryWrapper<AccidentHandle> query = Wrappers.lambdaQuery();
        query.eq(AccidentHandle::getAccidentId,accidentHandle.getAccidentId());
        List<AccidentHandle> handleList = accidentHandleMapper.selectList(query);
        if(handleList.size() > 0 || !handleList.isEmpty()){
            throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
        }

        List<AccidentHandleSurveyTeam> reviewerList = accidentHandleDTO.getReviewerList();

        //处理第一责任人和第二责任人
        List<SysUser> firstDutyList = accidentHandleDTO.getFirstDutyList();
        String firstDuty = "";
        for (SysUser sysUser : firstDutyList) {
            firstDuty += sysUser.getId();
            firstDuty += ",";
        }

        accidentHandle.setFirstDuty(firstDuty);

        List<SysUser> secondDutyList = accidentHandleDTO.getSecondDutyList();
        String secondDuty = "";
        for (SysUser sysUser : secondDutyList) {
            secondDuty += sysUser.getId();
            secondDuty += ",";
        }

        accidentHandle.setSecondDuty(secondDuty);

        //添加事故处理信息
        int result = accidentHandleMapper.insert(accidentHandle);

        if(result == 0){
            throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
        }

        //添加调查组信息
        for (AccidentHandleSurveyTeam reviewer : reviewerList) {

            AccidentHandleSurveyTeam surveyTeam = new AccidentHandleSurveyTeam();
            BeanUtils.copyProperties(reviewer,surveyTeam);
            surveyTeam.setAccidentHandleId(accidentHandle.getId());
            int res = accidentHandleSurveyTeamMapper.insert(surveyTeam);
            if(res == 0){
                throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
            }
        }

        //修改事故处理状态
        AccidentMessage accidentMessage = accidentMessageMapper.selectById(accidentHandle.getAccidentId());
        if(accidentMessage == null){
            throw new CustomizeException(GeneralResponseEnums.ADD_FAILED);
        }
        accidentMessage.setHandleStatus(1);
        accidentMessageMapper.updateById(accidentMessage);

        return true;
    }

    /**
     * 更新事故处理信息
     * @param accidentHandleDTO
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean updateHandleMsgById(AccidentHandleDTO accidentHandleDTO){
        AccidentHandle accidentHandle = accidentHandleDTO.getAccidentHandle();
        List<AccidentHandleSurveyTeam> reviewerList = accidentHandleDTO.getReviewerList();

        //修改第一责任人和第二责任人
        List<SysUser> firstDutyList = accidentHandleDTO.getFirstDutyList();
        String firstDuty = "";
        for (SysUser sysUser : firstDutyList) {
            firstDuty += sysUser.getId();
            firstDuty += ",";
        }

        accidentHandle.setFirstDuty(firstDuty);

        List<SysUser> secondDutyList = accidentHandleDTO.getSecondDutyList();
        String secondDuty = "";
        for (SysUser sysUser : secondDutyList) {
            secondDuty += sysUser.getId();
            secondDuty += ",";
        }

        accidentHandle.setSecondDuty(secondDuty);


        //更新事故处理信息
        int res1 = accidentHandleMapper.updateById(accidentHandle);
        if(res1 == 0){
            throw new CustomizeException(GeneralResponseEnums.UPDATE_FAILED);
        }

        //删除小表
        LambdaQueryWrapper<AccidentHandleSurveyTeam> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AccidentHandleSurveyTeam::getAccidentHandleId,accidentHandle.getId());
        List<AccidentHandleSurveyTeam> accidentHandleSurveyTeams = accidentHandleSurveyTeamMapper.selectList(queryWrapper);

        for (AccidentHandleSurveyTeam obj : accidentHandleSurveyTeams) {
            accidentHandleSurveyTeamMapper.deleteById(obj.getId());
        }

        //重新添加小表
        for (AccidentHandleSurveyTeam surveyTeam : reviewerList) {
            AccidentHandleSurveyTeam obj = new AccidentHandleSurveyTeam();
            BeanUtils.copyProperties(surveyTeam,obj);
            obj.setAccidentHandleId(accidentHandle.getId());
            int res2 = accidentHandleSurveyTeamMapper.insert(obj);
            if(res2 == 0) {
                throw new CustomizeException(GeneralResponseEnums.UPDATE_FAILED);
            }
        }

        return true;
    }

    /**
     * 条件查询
     * @param accidentHandleQO
     * @return
     */
    public IPage<AccidentHandleVO> getListByQO(AccidentHandleQO accidentHandleQO){
        Page<AccidentHandleVO> page = new Page<>(accidentHandleQO.getCurrent(),accidentHandleQO.getSize());

        //排序
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);

        IPage<AccidentHandleVO> list = accidentHandleMapper.getListByQO(page, accidentHandleQO);
        list.getRecords().forEach(
                vo -> {
                    vo.setDepartmentName(vo.getDepartmentName() == null ? "该部门不存在" : vo.getDepartmentName());
                    vo.setCreatorName(vo.getCreatorName() == null ? "该用户不存在" : vo.getCreatorName());
                }
        );

        return list;
    }

    /**
     *根据id删除事故调查处理记录
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean deleteByIds(Long[] ids){

        if(ids == null || ids.length == 0){
            return true;
        }

        for (Long id : ids) {

            LambdaQueryWrapper<AccidentHandleSurveyTeam> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(AccidentHandleSurveyTeam::getAccidentHandleId,id);
            List<AccidentHandleSurveyTeam> teams = accidentHandleSurveyTeamMapper.selectList(queryWrapper);

            if(!teams.isEmpty() && teams.size()>0){
                for (AccidentHandleSurveyTeam team : teams) {
                    accidentHandleSurveyTeamMapper.deleteById(team.getId());
                }
            }

            int res = accidentHandleMapper.deleteById(id);
            if(res == 0){
                throw new CustomizeException(GeneralResponseEnums.DELETE_FAILED);
            }
        }

        return true;
    }

    /**
     * 根据事故id查询事故处理信息
     * @param id
     * @return
     */
    public AccidentHandleVO getById(Long id){
        AccidentHandleVO vo = new AccidentHandleVO();

        //获取事故的基本信息
        AccidentMessage accidentMessage = accidentMessageMapper.selectById(id);
        if(accidentMessage == null){
            throw new CustomizeException(GeneralResponseEnums.GET_FAILED);
        }
        vo.setAccidentMessage(accidentMessage);
        if(accidentMessage.getHandleStatus() == 0){
            return vo;
        }

        //根据事故id获取事故处理信息
        LambdaQueryWrapper<AccidentHandle> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AccidentHandle::getAccidentId,id);
        List<AccidentHandle> accidentHandleList = accidentHandleMapper.selectList(queryWrapper);
        if(accidentHandleList.size()==0 || accidentHandleList.isEmpty()){
            throw new CustomizeException(GeneralResponseEnums.GET_FAILED);
        }

        AccidentHandle accidentHandle = accidentHandleList.get(0);
        BeanUtils.copyProperties(accidentHandle,vo);

        List<SurveyMemberVO> surveyMemberVOList = new ArrayList<>();

        //获取调查组人员信息
        LambdaQueryWrapper<AccidentHandleSurveyTeam> query = Wrappers.lambdaQuery();
        query.eq(AccidentHandleSurveyTeam::getAccidentHandleId,accidentHandle.getId());
        List<AccidentHandleSurveyTeam> surveyTeamList = accidentHandleSurveyTeamMapper.selectList(query);

        for (AccidentHandleSurveyTeam surveyTeam : surveyTeamList) {
            SysUser sysUser = sysUserMapper.selectById(surveyTeam.getMemberId());

            if (sysUser == null) {
                continue;
            }

            //获取部门名称
            String orgids = sysUser.getOrgids();
            long[] orgidsArray = Arrays.stream(orgids.split(",")).mapToLong(Long::parseLong).toArray();
            List<String> departmentNames = Arrays.stream(orgidsArray).mapToObj(tmp_id -> {
                Organization organization = organizationMapper.selectById(tmp_id);
                return organization == null ? "该部门已被删除" : organization.getName();
            }).collect(Collectors.toList());

            SurveyMemberVO surveyMemberVO = new SurveyMemberVO();
            surveyMemberVO.setDepartments(departmentNames);
            surveyMemberVO.setFun(surveyTeam.getFun());
            surveyMemberVO.setSurveyMember(sysUser);

            surveyMemberVOList.add(surveyMemberVO);
        }

        //第一责任人和第二责任人
        String firstDuty = accidentHandle.getFirstDuty();
        long[] firstDutyArray = Arrays.stream(firstDuty.split(",")).mapToLong(Long::parseLong).toArray();
        List<String> firstDutyList = Arrays.stream(firstDutyArray).mapToObj(tmp_id -> {
            SysUser user = sysUserMapper.selectById(tmp_id);
            return user==null ? "":user.getName();
        }).collect(Collectors.toList());

        String firstDutyName = Joiner.on(",").join(firstDutyList);
        vo.setFirstDutyName(firstDutyName);

        String secondDuty = accidentHandle.getSecondDuty();
        long[] secondDutyArray = Arrays.stream(secondDuty.split(",")).mapToLong(Long::parseLong).toArray();
        List<String> secondDutyList = Arrays.stream(secondDutyArray).mapToObj(tmp_id -> {
            SysUser user = sysUserMapper.selectById(tmp_id);
            return user==null ? "":user.getName();
        }).collect((Collectors.toList()));

        String secondDutyName = Joiner.on(",").join(secondDutyList);
        vo.setSecondDutyName(secondDutyName);

        //vo.setCreatorName(sysUserMapper.selectById(accidentHandle.getCreator()).getName());//上报人姓名
        //vo.setFirstDutyName(sysUserMapper.selectById(accidentHandle.getFirstDuty()).getName());//第一责任人
        //vo.setSecondDutyName(sysUserMapper.selectById(accidentHandle.getSecondDuty()).getName());//第二责任人
        vo.setSurveyTeamMsgList(surveyMemberVOList);//调查组人员信息

        return vo;
    }
}
